<template>
  <div id="addQuestionView">
    <h2 v-if="updateFlag" style="text-align: center">更新题目</h2>
    <h2 v-else style="text-align: center">创建题目</h2>
    <a-row>
      <a-col :flex="4"></a-col>
      <a-col :flex="4">
        <a-space direction="vertical" size="large">
          <a-form :model="form" layout="vertical">
            <!--标题-->
            <a-form-item field="title" label="标题" tooltip="题目的标题">
              <a-input v-model="form.title" placeholder="请输入标题" />
            </a-form-item>
            <!--标签-->
            <a-form-item field="tags" label="标签" tooltip="题目的标签">
              <a-input-tag
                v-model="form.tags"
                placeholder="请选择标签"
                allow-clear
              />
            </a-form-item>
            <!--题目内容-->
            <a-form-item
              field="content"
              label="题目内容"
              tooltip="以下为模板内容，可自行修改"
            >
              <MdEditor
                :value="form.content"
                :handle-change="onContentChange"
                :upload-images="uploadImages"
                style="min-width: 900px"
              />
            </a-form-item>
            <!--题目答案-->
            <a-form-item
              field="answer"
              label="题目答案"
              tooltip="请直接在模板中添加答案"
            >
              <MdEditor
                :value="form.answer"
                mode="tab"
                :handle-change="onAnswerChange"
                :upload-images="uploadImages"
                style="min-width: 900px"
              />
            </a-form-item>
            <!--判题配置-->
            <a-form-item
              label="判题配置"
              :content-flex="false"
              :merge-props="false"
              tooltip="题目的判题配置"
            >
              <!--时间限制-->
              <a-form-item
                field="from.judgeConfig.timeLimit"
                label="时间限制（ms）"
              >
                <!--时间限制-->
                <a-input-number
                  v-model="form.judgeConfig.timeLimit"
                  placeholder="请输入时间限制"
                  mode="button"
                  size="large"
                />
              </a-form-item>
              <!--内存限制-->
              <a-form-item
                field="from.judgeConfig.memoryLimit"
                label="内存限制（KB）"
              >
                <a-input-number
                  v-model="form.judgeConfig.memoryLimit"
                  placeholder="请输入内存限制"
                  mode="button"
                  size="large"
                />
              </a-form-item>
              <!--堆栈限制-->
              <a-form-item
                field="from.judgeConfig.stackLimit"
                label="堆栈限制（KB）"
              >
                <a-input-number
                  v-model="form.judgeConfig.stackLimit"
                  placeholder="请输入堆栈限制"
                  mode="button"
                  size="large"
                />
              </a-form-item>
            </a-form-item>
            <!--测试用例配置-->
            <a-form-item
              label="测试用例配置"
              :content-flex="false"
              :merge-props="false"
              tooltip="题目的测试用例配置"
            >
              <a-form-item
                v-for="(judgeCaseItem, index) of form.judgeCase"
                :key="index"
                no-style
              >
                <div :style="{ display: 'flex' }">
                  <a-card
                    :style="{ width: '900px' }"
                    :title="`测试用例（${index + 1}）`"
                  >
                    <template #extra>
                      <a-link status="danger" @click="handleDelete(index)">
                        删除
                      </a-link>
                    </template>
                    <a-form-item
                      :field="`form.judgeCase[${index}].inputCase`"
                      label="输入用例"
                      :key="index"
                    >
                      <a-input
                        v-model="judgeCaseItem.inputCase"
                        placeholder="请输入 测试输入用例"
                      />
                    </a-form-item>
                    <a-form-item
                      :field="`form.judgeCase[${index}].output`"
                      label="输出用例"
                      :key="index"
                      style="margin-bottom: 0"
                    >
                      <a-input
                        v-model="judgeCaseItem.outputCase"
                        placeholder="请输入 测试输出用例"
                      />
                    </a-form-item>
                  </a-card>
                </div>
                <br />
              </a-form-item>
              <!--新增测试用例-->
              <a-button
                shape="round"
                @click="handleAdd"
                type="outline"
                status="success"
              >
                新增测试用例
              </a-button>
            </a-form-item>
            <!--提交-->
            <a-button
              type="primary"
              shape="round"
              @click="doSubmit"
              :loading="loadStatus"
            >
              提交
            </a-button>
          </a-form>
        </a-space>
      </a-col>
      <a-col :flex="4"></a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { useRoute, useRouter } from "vue-router";
import { QuestionControllerService } from "../../../generated";
import { Message } from "@arco-design/web-vue";
import axios from "axios";
import { baseUrl } from "@/plugins/axios";

const route = useRoute();
const router = useRouter();

// 点击提交加载状态
const loadStatus = ref(false);

/**
 * 添加题目表单
 */
let form = ref({
  title: "",
  tags: [],
  content:
    "## 描述\n" +
    "\n" +
    "\n" +
    "## 输入\n" +
    "\n" +
    "\n" +
    "## 输出\n" +
    "\n" +
    "\n" +
    "## 示例输入\n" +
    "\n" +
    "\n" +
    "## 示例输出\n" +
    "\n" +
    "\n" +
    "## 提示\n",
  answer:
    "public class Main {\n" +
    "    public static void main(String[] args) {\n" +
    "        \n" +
    "    }\n" +
    "}",
  judgeConfig: {
    timeLimit: 1000,
    memoryLimit: 1000,
    stackLimit: 1000,
  },
  judgeCase: [
    {
      inputCase: "",
      outputCase: "",
    },
  ],
});

// 判断是新增还是更新
const updateFlag = route.path.includes("update");

/**
 * 根据题目id，加载数据
 */
const loadData = async () => {
  if (!updateFlag) return;
  const questionId = route.query.id;
  if (!questionId) {
    Message.error("未获取到题目id");
    await router.push("/question/manage");
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    questionId as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    // JSON字符串解析为JavaScript对象
    form.value.tags = JSON.parse(res.data?.tags as any);
    form.value.judgeCase = JSON.parse(res.data?.judgeCase as any);
    form.value.judgeConfig = JSON.parse(res.data?.judgeConfig as any);
  } else {
    Message.error("糟糕，没找到你要的题目！" + res.message);
  }
};

/**
 * 组件渲染成功，调用加载数据函数
 */
onMounted(() => {
  loadData();
});

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    inputCase: "",
    outputCase: "",
  });
};

/**
 * 删除判题用例
 * @param index 删除的判题用例下标
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};

/**
 * 在题目内容改变时触发
 * @param value 新的题目内容
 */
const onContentChange = (value: string) => {
  form.value.content = value;
};

/**
 * 在题目答案改变时触发
 * @param value 新的题目答案
 */
const onAnswerChange = (value: string) => {
  form.value.answer = value;
};

/**
 * 点击提交时触发
 */
const doSubmit = async () => {
  loadStatus.value = true;
  // 判断是更新还是新增
  if (updateFlag) {
    // 更新
    const res = await QuestionControllerService.updateQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      Message.success("更新题目成功！");
    } else {
      Message.error("更新题目失败，" + res.message);
    }
  } else {
    // 新增
    const res = await QuestionControllerService.addQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      Message.success("创建题目成功！");
    } else {
      Message.error("创建题目失败，" + res.message);
    }
  }
  loadStatus.value = false;
};

/**
 * 上传图片
 * @param file 图片文件
 */
const uploadImages = async (file: any) => {
  const formData = new FormData();
  formData.append("file", file[0]);

  const res = await axios.post(baseUrl + "/api/file/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  if (res.data.code === 0) {
    return [{ url: res.data.data }];
  } else {
    Message.error("上传图片失败，" + res.data.message);
    return [{ url: "" }];
  }
};
</script>

<style scoped></style>
